package com.lele.js;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;

import com.lele.util.FolderUtil;


public class ModelJS extends SuperJS {
	public ModelJS(SuperJS sf){
		this.entityName = sf.getEntityName();
		this.entityClass = sf.getEntityClass();
		this.file_url = sf.getProject_root()+"leleCMS\\WebRoot\\admin\\FMApp\\"+entityClass+"App\\model\\"+entityClass+"Model.js";
		this.fields = sf.getFields();
	}
	public String getFileURL() {
		return file_url;
	}

	public String getContent(){
		StringBuilder new_actions = new StringBuilder();
		try {
			new_actions.append(FolderUtil.readTxt(
					this.getFileURL().toString(), "UTF-8"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (new_actions.toString().equals("")) {
			String build = System.getProperty("user.dir")
					+ "\\src\\template\\RoleModel.txt";
			try {
				new_actions.append(FolderUtil.readTxt(build.toString(), "UTF-8").replace("Role", entityClass)
						.replace("role", entityName));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		StringBuilder actions_str = new StringBuilder();
		if (fields.size()>0) {
			Set<Entry<String, String>> maps = fields.entrySet();
	        Iterator<Entry<String, String>> temps = maps.iterator();
	        int i = 0;
	        while (temps.hasNext())
	        {
	            Entry<String, String> keys1 = (Entry<String, String>)temps.next();
	            String value = keys1.getKey();
	            String Key = fields.get(value);
	            //System.out.println(Key+":"+value);
	            if (Key.equals("Char")) {
	            	Key = "string";
				}
	           
	            if (Key.indexOf("|PK")>0) {
					Key = Key.substring(0,Key.indexOf("|PK"));
				}
	            if(Key.equals("Integer")){
	            	Key = "int";
	            }
	            actions_str = actions_str
					.append("        {name:\"")
					.append(value)
					.append("\",type:\"")
					.append(Key)
					.append("\",srotable:true}");
	            if((i+1)!=maps.size()){
	            	actions_str.append(",");
	            }
	            actions_str.append("\r\n");
	            i++;
	        }
		}
		new_actions.insert(new_actions.indexOf("//fields auto end"),
					actions_str.toString());
		return new_actions.toString();
	}
}
